package com.audaque.springboot.foshanupload.security.valid.filter;

import com.audaque.springboot.foshanupload.security.valid.provider.UserVerifyAuthenticationProvider;
import com.audaque.springboot.foshanupload.security.valid.rsp.login.MyAuthenticationFailureHandler;
import com.audaque.springboot.foshanupload.security.valid.rsp.login.MyAuthenticationSuccessHandler;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    private UserVerifyAuthenticationProvider authenticationManager;

    /**
     * @param authenticationManager 认证管理器
     * @param successHandler        认证成功处理类
     * @param failureHandler        认证失败处理类
     */
    public LoginFilter(UserVerifyAuthenticationProvider authenticationManager,
                       MyAuthenticationSuccessHandler successHandler,
                       MyAuthenticationFailureHandler failureHandler,
                       String loginUrl) {
        //设置认证管理器(对登录请求进行认证和授权)
        this.authenticationManager = authenticationManager;
        //设置认证成功后的处理类
        this.setAuthenticationSuccessHandler(successHandler);
        //设置认证失败后的处理类
        this.setAuthenticationFailureHandler(failureHandler);
        //可以自定义登录请求的url
        super.setFilterProcessesUrl(loginUrl);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //转换请求入参
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        return authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, password)
        );
    }
}